package com.yonyougov.cruxtestcase.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.yonyougov.cruxtestcase.testcase.logincase.dto.GetTokenResponseDto;

@Component
public class CommonLogin {
    @Autowired
    private RestTemplate restTemplate;

    public String getToken(String baseUrl, String username, String password) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization", "Basic bXlpZDpteXNlY3JldA==");
        headers.set("X-Requested-With", "XMLHttpRequest");

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", username);
        map.add("password", password);
        map.add("grant_type", "password");
        map.add("scope", "read");
        HttpEntity<MultiValueMap<String, String>> requestBody = new HttpEntity<>(map, headers);
        ResponseEntity<GetTokenResponseDto> response = restTemplate.exchange(baseUrl + "/crux-auth/oauth/token", HttpMethod.POST, requestBody, GetTokenResponseDto.class);
        if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
            GetTokenResponseDto tokenDto = response.getBody();
            assert tokenDto != null;
            return tokenDto.getAccess_token();
        }
        return null;
    }
}
